/*
  Copyright 2011 Jonathan Albarrán León

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.jaal.movilconsultanet.asynctasks;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.jaal.movilconsultanet.Progreso;
import com.jaal.movilconsultanet.R;
import com.jaal.movilconsultanet.SessionCookie;
import com.jaal.movilconsultanet.Util;
import com.jaal.movilconsultanet.XMLContent;
import com.jaal.movilconsultanet.activities.Consulta;
import com.jaal.movilconsultanet.activities.MovilConsultaNet;

public class GSMSessionStarter extends AsyncTask<String, Progreso, Boolean> {

	MovilConsultaNet mainActivity;
	ProgressDialog progreso;
	Progreso progresoInfo = new Progreso();
	private Map<String, String> requestParams;
	private String captchaText = null;
	String numero, password, codTlf;

	public GSMSessionStarter(MovilConsultaNet mainActivity) {
		this.mainActivity = mainActivity;
	}


	@Override
	protected void onPreExecute() {

		progreso = new ProgressDialog(mainActivity);
		progreso.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progreso.setProgress(0);
		progreso.setMessage(mainActivity.getResources().getText(R.string.connection_connecting_server));
		progreso.setCancelable(false);
		progreso.show();
	}


	@Override
	protected Boolean doInBackground(String... urls) {

		Log.d("MCN", "GSMSessionStarter - inicio");
		// le paso el captcha cuando hago claseAsync.execute(captcha)
		captchaText = urls[0];
		SessionCookie sessionCookie = mainActivity.getSessionCookie();
		HttpURLConnection connection = null;

		progresoInfo.setProgreso(10);
		progresoInfo.setMensaje(mainActivity,R.string.connection_prepare);
		publishProgress(progresoInfo);

		String urlParameters = prepareRequestParams();
		try {
			urlParameters = Util.createURLParameters(requestParams);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		Log.d("MCN", "startSession - urlParams" + urlParameters);

		Log.d("MCN",
				"startSession - sessionCookie: "
				+ sessionCookie.getSessionCookie());

		Log.d("MCN", "loginGSM - inicio");
		// sessionCookie.checkSessionCookie();

		URL url;
		try {
			// Create connection
			String targetURL = "https://www.movilnet.com.ve/agl/Controller";
			url = new URL(targetURL);
			Log.d("MCN", "loginGSM - conectando..." + targetURL);

			progresoInfo.setProgreso(30);
			progresoInfo.setMensaje(mainActivity,R.string.connection_connecting);
			publishProgress(progresoInfo);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type",
			"application/x-www-form-urlencoded");
			connection.setRequestProperty("Content-Length",
					"" + Integer.toString(urlParameters.getBytes().length));
			connection.setRequestProperty("Content-Language", "en-US");
			Log.d("MCN",
					"loginGSM - setCookie: " + sessionCookie.getSessionCookie());
			connection.setRequestProperty("Cookie",
					sessionCookie.getSessionCookie());
			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setConnectTimeout(5000);

			Log.d("MCN", "loginGSM - sending request...");
			// Send request
			progresoInfo.setProgreso(50);
			progresoInfo.setMensaje(mainActivity,R.string.connection_send);
			publishProgress(progresoInfo);
			DataOutputStream wr = new DataOutputStream(
					connection.getOutputStream());
			wr.writeBytes(urlParameters);
			wr.flush();
			wr.close();

			Log.d("MCN", "loginGSM - getting response...");
			// Get Response
			progresoInfo.setProgreso(60);
			progresoInfo.setMensaje(mainActivity,R.string.connection_response_verify);
			publishProgress(progresoInfo);

			String location = null;
			if ((location = connection.getHeaderField("location")) == null) {
				progresoInfo.setError(true);
				progresoInfo
				.setMensaje(mainActivity,R.string.session_error);
				publishProgress(progresoInfo);
				return false;
			}

			// ahora si me dispongo a hacer el inicio de sesion
			// Create connection
			targetURL = "http://www.movilnet.com.ve/agl/gsm/login.action";
			url = new URL(targetURL);
			Log.d("MCN", "getGSMSession - conectando..." + targetURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type",
			"application/x-www-form-urlencoded");
			urlParameters = Util.getGSMSessionParameter(location);
			Log.d("MCN", "getGSMSession - GSMSessionParameter: "
					+ urlParameters);

			connection.setRequestProperty("Content-Length",
					"" + Integer.toString(urlParameters.getBytes().length));
			connection.setRequestProperty("Content-Language", "en-US");

			Log.d("MCN",
					"getGSMSession - setCookie: "
					+ sessionCookie.getSessionCookie());

			connection.setRequestProperty("Cookie",
					sessionCookie.getSessionCookie());

			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);

			connection.setConnectTimeout(5000);

			Log.d("MCN", "getGSMSession - sending request");

			progresoInfo.setProgreso(75);
			progresoInfo.setMensaje(mainActivity,R.string.session_starting);
			publishProgress(progresoInfo);

			// Send request
			wr = new DataOutputStream(connection.getOutputStream());
			wr.writeBytes(urlParameters);
			wr.flush();
			wr.close();

			Log.d("MCN", "getGSMSession - NEW connection sessionCookie: "
					+ connection.getHeaderField(3));
			// tomo una nueva sesion para el gsm
			sessionCookie.setSessionCookie(connection.getHeaderField(3));

			Log.d("MCN",
					"getGSMSession - NEW sessionCookie: "
					+ sessionCookie.getSessionCookie());

			progresoInfo.setProgreso(85);
			progresoInfo.setMensaje(mainActivity,R.string.session_started);
			publishProgress(progresoInfo);

			sessionCookie.setGSMSessionStarted(true);

			progresoInfo.setProgreso(95);
			progresoInfo.setMensaje(mainActivity,R.string.configuration_saving);
			publishProgress(progresoInfo);
			// para generar el xml y guardar los datos de la sesion
			String contenido = "sesiones";
			HashMap<String, String> data = new HashMap<String, String>();

			// guardo el session id DEFINITIVO
			data.put("session_id", sessionCookie.getSessionCookie());
			data.put("session_started",
					sessionCookie.isGSMSessionStarted() ? "true" : "false");
			data.put("number", numero);
			data.put("code", Util.getCodTlfMovilnet(codTlf));
			data.put("password", password);
			data.put("mobile_id", urlParameters);

			XMLContent.saveXML(contenido, data);

			Log.d("MCN", "getGSMSession - data saved: " + data);

			progresoInfo.setProgreso(100);
			progresoInfo.setFinished(true);
			progresoInfo.setMensaje(mainActivity,R.string.connection_final);
			publishProgress(progresoInfo);

			Log.d("MCN", "startSession - fin");

		} catch (ConnectException e) {
			progresoInfo.setError(true);
			progresoInfo.setMensaje(mainActivity,R.string.connection_error);
			publishProgress(progresoInfo);
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			progresoInfo.setError(true);
			progresoInfo
			.setMensaje(mainActivity,R.string.connection_error_server);
			publishProgress(progresoInfo);
		} catch (IOException e) {
			e.printStackTrace();
			progresoInfo.setError(true);
			progresoInfo.setMensaje(mainActivity,R.string.connection_error_io);
			publishProgress(progresoInfo);
		} finally {
			if (connection != null) {
				Log.d("MCN", "getGSMSession - desconectando...");
				connection.disconnect();
			}
		}
		return true;
	}

	@Override
	protected void onProgressUpdate(Progreso... values) {

		Progreso mProgresoInfo = values[0];

		if (!mProgresoInfo.isError()) {
			progreso.setProgress(mProgresoInfo.getProgreso());
			progreso.setMessage(mProgresoInfo.getMensaje());

			if (mProgresoInfo.isFinished()) {
				progreso.dismiss();
			}

		} else {
			progreso.dismiss();
			Toast.makeText(mainActivity, mProgresoInfo.getMensaje(),
					Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	protected void onPostExecute(Boolean result) {

		if (progresoInfo.isError()) {
			return;
		}
		Intent i = new Intent(mainActivity, Consulta.class);
		mainActivity.startActivity(i);
	}

	private String prepareRequestParams() {
		Log.d("MCN", "prepareRequest - inicio");

		password = mainActivity.passwordField.getText().toString().trim();
		numero = mainActivity.numeroField.getText().toString().trim();
		codTlf = Util.getCodTlf(mainActivity.codigoTlfField.getSelectedItem()
				.toString());

		requestParams = new HashMap<String, String>();
		/*
		 * 0416 -> 158 0426 -> 199
		 */
		requestParams.put("prefijo", codTlf);
		requestParams.put("numero", numero);
		requestParams.put("clave", password);
		// requestParams.put("servicio", "cantvnet");
		requestParams.put("codigo", captchaText);

		Log.d("MCN",
				"prepareRequest - requestParams: " + requestParams.toString());

		Log.d("MCN", "prepareRequest - fin");

		try {
			return Util.createURLParameters(requestParams);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;

	}

}
